package com.run.go.gearbox.mysql;

import com.run.go.gearbox.core.transmission.ExecuteEntity;
import com.run.go.gearbox.core.transmission.AbstractTransmission;
import com.run.go.gearbox.core.transmission.ResultCallBack;
import com.run.go.gearbox.mysql.codec.*;
import com.run.go.gearbox.mysql.handler.MysqlNettyHandler;
import com.run.go.gearbox.mysql.handler.MysqlNettyOutHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * mysql 真个八经的连接
 */
public class MysqlTransmission extends AbstractTransmission {

    private String host;

    private Integer port;

    private volatile Channel channel;

    private Encoder encoder;

    private Decoder decoder;

    public MysqlTransmission(String host,Integer port) {
        encoder = new MysqlEncoder();
        this.host = host;
        this.port = port;
    }

    public final String ENCODER = MysqlTransmission.class.getName() + ".encoder";


    @Override
    public void start() {
        if(start.get() == 1){
            /* 已经启动 */
            return;
        }
        /* 如果不是真 就说明已经启动了 */
        if(start.compareAndSet(0,1)){
            Bootstrap bootstrap = new Bootstrap()
                    .group(new  NioEventLoopGroup())
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.AUTO_READ, false)
                    .remoteAddress(host, port)
                    .handler(new ChannelInitializer() {
                        @Override
                        public void initChannel(Channel ch) throws Exception {
                            ch.config().setAutoRead(true);
                            ch.pipeline().addLast(ENCODER, new NettyMysqlEncoder(encoder));
                            ch.pipeline().addLast(new MysqlNettyHandler());
                            ch.pipeline().addLast(new MysqlNettyOutHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect();
            channel = channelFuture.channel();
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public void send(ExecuteEntity executeEntity, ResultCallBack resultCallBack) {

    }

    @Override
    public Boolean transmissionStarted() {
        return null;
    }

    @Override
    public void close() {
        super.close();
    }


}
